import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './runtime.less'
import { loadJs } from '../utils'
const ready = loadJs('http://api.tianditu.gov.cn/api?v=4.0&tk=6c7e4c383394453f5a42bdc42d9e7554')
export default function ({ env, data, inputs, outputs, slots, style }: any) {
  const containerRef = useRef<HTMLDivElement>(null)
  const mapRef = useRef<any>(null)
  const cpRef = useRef<any>(null)
  const polygonRef = useRef<any>(null)
  useEffect(() => {
    ready.then(() => {
      const container = containerRef.current
      if(!container) return
      const lng = data.lng || 116.40769
      const lat = data.lat ||  39.89945
      //初始化地图对象
      const map = new window.T.Map(container,  {
        projection: 'EPSG:4326'
      });
      //设置显示地图的中心点和级别
      map.centerAndZoom(new window.T.LngLat(lng, lat), 12);
      mapRef.current = map
    })
  }, [])

  // 开启坐标拾取
  const openCoordinatePickup = () => {
    if (cpRef.current || !mapRef.current) return
    const cp = new window.T.CoordinatePickup(mapRef.current, {
      callback: (evt) => {
        outputs['onPositionPick']?.(evt)
      }
    })
    cp.addEvent();
    cpRef.current = cp
  }

  // 关闭坐标拾取
  const closeCoordinatePickup = () => {
    if (!cpRef.current) return
    cpRef.current.removeEvent();
    cpRef.current = null
  }



  // 开启多边形工具
  const openPolygonTool = () => {
    if(!mapRef.current) return
    closeCoordinatePickup()
    if (polygonRef.current) polygonRef.current.close();
    const polygon = new window.T.PolygonTool(mapRef.current);
    polygon.open();
    polygon.addEventListener('draw', (evt) => {
      outputs['onPolygonPick']?.(evt.currentLnglats)
    })
    polygonRef.current = polygon
  }

  // 清空绘制的多边形
  const clearPolygonTool = () => {
    if (mapRef.current) mapRef.current.clearOverLays();
  }

  /** 运行时 */
  return (
    <div className={styles.mapContainer} style={{width:style.width, height: style.height}}>
        <div className={styles.map} ref={containerRef}/>
        <div className={styles.tools}>
          <div className={styles.toolsBtn} onClick={openCoordinatePickup}>坐标拾取器</div>
          <div className={styles.toolsBtn} onClick={openPolygonTool}>多边形工具</div>
          <div className={styles.toolsBtn} onClick={clearPolygonTool}>清空</div>
        </div>
      </div>
  )
}
